package com.common.springbootcommonmessage.service.impl;

import com.common.springbootcommonmessage.entity.SiteUser;
import com.common.springbootcommonmessage.enums.AutoBestErrorCode;
import com.common.springbootcommonmessage.exceptions.AutoBestException;
import com.common.springbootcommonmessage.mapper.CommonAutopartNotificationMapper;
import com.common.springbootcommonmessage.mapper.CommonAutopartNotificationchangetopichistoryMapper;
import com.common.springbootcommonmessage.mapper.CommonAutopartNotificationitemMapper;
import com.common.springbootcommonmessage.mapper.CommonAutopartNotificationtemplateMapper;
import com.common.springbootcommonmessage.mapper.CommonAutopartOrderitemMapper;
import com.common.springbootcommonmessage.mapper.CommonAutopartOrderitemhistoryMapper;
import com.common.springbootcommonmessage.mapper.CommonAutopartOrdersMapper;
import com.common.springbootcommonmessage.model.CommonAutopartNotification;
import com.common.springbootcommonmessage.model.CommonAutopartNotificationchangetopichistory;
import com.common.springbootcommonmessage.model.CommonAutopartNotificationitem;
import com.common.springbootcommonmessage.model.CommonAutopartNotificationtemplate;
import com.common.springbootcommonmessage.model.CommonAutopartOrderitem;
import com.common.springbootcommonmessage.model.CommonAutopartOrderitemhistory;
import com.common.springbootcommonmessage.model.CommonAutopartOrders;
import com.common.springbootcommonmessage.service.CommonNotificationService;
import com.common.springbootcommonmessage.service.CommonOrderService;
import com.common.springbootcommonmessage.utils.LogUtil;
import com.common.springbootcommonmessage.vo.NotificationTemplateVo;
import com.common.springbootcommonmessage.vo.NotificationVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author korol *
 * @date 2022年12月08日 15:27
 */
@Service
public class CommonNotificationServiceImpl implements CommonNotificationService {
    @Autowired
    private CommonAutopartNotificationMapper commonAutopartNotificationMapper;
    @Autowired
    private CommonAutopartNotificationtemplateMapper commonAutopartNotificationtemplateMapper;
    @Autowired
    private CommonAutopartOrderitemhistoryMapper commonAutopartOrderitemhistoryMapper;
    @Autowired
    private CommonOrderService commonOrderService;
    @Autowired
    private CommonAutopartOrderitemMapper commonAutopartOrderitemMapper;
    @Autowired
    private CommonAutopartNotificationitemMapper commonAutopartNotificationitemMapper;
    @Autowired
    private CommonAutopartNotificationchangetopichistoryMapper notificationchangetopichistoryMapper;
    @Autowired
    private CommonAutopartOrdersMapper commonAutopartOrdersMapper;
    @Override
    public List<NotificationVo> getList(SiteUser user, Integer orderId, Integer rmaId, Boolean isNew, String traceId) {
        List<CommonAutopartNotification> notificationList = commonAutopartNotificationMapper.findByOrderIDAndRmaIDAndIsNew(orderId, rmaId, isNew);
        return NotificationVo.transferToVoList(notificationList);
    }

    @Override
    public NotificationTemplateVo changeTopicItem(SiteUser siteUser, Integer orderId, Integer notificationId, Integer templateId, String traceId) throws AutoBestException {
        String message = "";
        CommonAutopartNotificationtemplate notificationTemplate = commonAutopartNotificationtemplateMapper.selectByPrimaryKey(templateId);
        if(null == notificationTemplate) {
            message = "NotificationTemplate-["+templateId+"] is not exsits.";
            LogUtil.logInfo(traceId, "OrderServiceImpl : changeTopicItem", "message : " + message, AutoBestErrorCode.RESOURCE_NOT_FOUND.getValue());
            // TODO:之前是 throw new AutoBestException(HttpStatus.EXPECTATION_FAILED, AutoBestErrorCode.RESOURCE_NOT_FOUND, message); 然后这边不太方便引入web包 就没发用httpStatus
            throw new AutoBestException(AutoBestErrorCode.RESOURCE_NOT_FOUND, message);
        }
        NotificationTemplateVo notificationTemplateVo = NotificationTemplateVo.transferToVo(notificationTemplate);
        CommonAutopartNotification notification = commonAutopartNotificationMapper.selectByPrimaryKey(notificationId);
        if(null == notification) {
            message = "Notification-["+notificationId+"] is not exsits.";
            LogUtil.logInfo(traceId, "OrderServiceImpl : changeTopicItem", "message : " + message, AutoBestErrorCode.RESOURCE_NOT_FOUND.getValue());
            throw new AutoBestException(AutoBestErrorCode.RESOURCE_NOT_FOUND, message);
        }
        commonAutopartNotificationMapper.updateTemplateIDByID(notificationId,templateId);
        //当选择的topic为PA Issue Follow up时，
        if(notificationTemplate.getIsPAIssueFollowUp()) {
            Integer groupId = commonAutopartOrderitemhistoryMapper.findMaxGroupIdFromOrderItemHistory();
            groupId = commonOrderService.getMaxGroupId(siteUser.getSite(),groupId);
            final List<CommonAutopartOrderitem> orderItemList = commonAutopartOrderitemMapper.findAllByOrderID(orderId);
            if(null != orderItemList && (orderItemList.size() > 0)) {
                for(int i = 0; i < orderItemList.size(); i++) {
                    CommonAutopartOrderitem orderItem = orderItemList.get(i);
                    CommonAutopartOrderitemhistory orderItemHistory = new CommonAutopartOrderitemhistory();
                    BeanUtils.copyProperties(orderItem, orderItemHistory);
                    orderItemHistory.setGroupID(commonOrderService.getMaxGroupId(siteUser.getSite(), groupId + 1 + i));
                    commonAutopartOrderitemhistoryMapper.insert(orderItemHistory);
                }
            }
            CommonAutopartNotificationitem notificationItem = commonAutopartNotificationitemMapper.findFirstByNotificationIDAndEventNo(notificationId, 1);
            if(null != notificationItem) {
                commonAutopartNotificationitemMapper.updateOrderItemHistoryID(notificationItem.getId(), groupId);
                commonOrderService.deleteMaxGroupIdKey(siteUser.getSite(), groupId);
            }
        }
        //记录客服对Topic的修改变更行为记录下来，作为Dealer 发Parts Issue Message选Topic是否正确的评估指标。
        //记录 修改的时间、操作员、针对的订单、Message ID、改成哪个Topic、操作员账号级别
        CommonAutopartNotificationchangetopichistory notificationChangeTopicHistory = new CommonAutopartNotificationchangetopichistory();
        notificationChangeTopicHistory.setNotificationID(notificationId);
        notificationChangeTopicHistory.setNotificationTemplateID(templateId);
        notificationChangeTopicHistory.setOrderID(orderId);
        notificationChangeTopicHistory.setOperatorID(siteUser.getId());
        notificationChangeTopicHistory.setOperatorRange(siteUser.getRange().getValue());
        notificationChangeTopicHistory.setProcessDate(new Date());
        notificationchangetopichistoryMapper.insert(notificationChangeTopicHistory);
        return notificationTemplateVo;
    }

    @Override
    public Boolean changeMessageReadStatus(SiteUser siteUser, Integer itemId, String traceId) throws AutoBestException {
        CommonAutopartNotificationitem notificationItem = commonAutopartNotificationitemMapper.selectByPrimaryKey(itemId);
        LogUtil.logInfo(traceId, "NotificationServiceImpl : changeMessageReadStatus", "itemId : " + itemId, "info");
        if(null == notificationItem) {
            String message = "NotificationItem-["+itemId+"] is not exists";
            LogUtil.logInfo(traceId, "OrderServiceImpl : changeMessageReadStatus", "message : " + message, AutoBestErrorCode.RESOURCE_NOT_FOUND.getValue());
            throw new AutoBestException(AutoBestErrorCode.RESOURCE_NOT_FOUND, message);
        }
        // 将该事件标记为read
        commonAutopartNotificationitemMapper.updateReadAndOperator(itemId, true, siteUser.getId(), siteUser.getUserName());

        List<CommonAutopartNotificationitem> notificationItemList = commonAutopartNotificationitemMapper.findAllNoReadByNotificationIDAndOperatorType(notificationItem.getNotificationID(), 0);
        LogUtil.logInfo(traceId, "NotificationServiceImpl : changeMessageReadStatus : notificationItemList", notificationItemList, "info");
        if(notificationItemList == null || notificationItemList.size() == 0 ) {
            CommonAutopartNotification notification = commonAutopartNotificationMapper.selectByPrimaryKey(notificationItem.getNotificationID());
            commonAutopartNotificationMapper.updateAllReadByID(notificationItem.getNotificationID(), true);
            final List<CommonAutopartNotification> notificationList = commonAutopartNotificationMapper.findNotAllReadByOrderIDAndRmaID(notification.getOrderID(), 0);
            LogUtil.logInfo(traceId, "NotificationServiceImpl : changeMessageReadStatus : notificationList", notificationList, "info");
            boolean hasUnRead = (null != notificationList && notificationList.size() > 0);
            commonAutopartOrdersMapper.updateHasUnRead(notification.getOrderID(), hasUnRead);
        }
        return true;
    }
}
